package com.jsmtr.rms.utils;

import org.hibernate.SessionFactory;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * hibernate的事件监听注册
 * @author: cyx
 * @description:
 * @date: Created in 2018/10/30 9:10
 * @modified by:
 */
 @Component
 public class HibernateEvent {

     @Autowired
     private SessionFactory sessionFactory;
     @Autowired
     private OperListener operListener;

             @PostConstruct
     public void registerListeners() {
                 EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(
                                 EventListenerRegistry.class);
                 registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(operListener);//对实体保存的监听
                 registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(operListener);//对实体修改的监听
                 registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(operListener);//对实体删除的监听
             }
 }
